import React, { useRef, useCallback } from 'react';
import { AgGridReact } from 'ag-grid-react';
import api from '../../utils/api';
const ServerSideGrid: React.FC = () => {
    const gridRef = useRef<any>(null);
    // 服务器端数据加载
    const onGridReady = useCallback(async (params: any) => {
        const dataSource = {
            getRows: async (params: any) => {
                try {
                    // 构建查询参数
                    const page = params.request.endRow / 100;
                    const pageSize = 100;
                    const sortModel = params.request.sortModel.map((item: any) => ({
                        field: item.colId,
                        sort: item.sort
                    }));
                    
                    // 发送API请求
                    const response = await api.post('/users/search', {
                        page,
                        pageSize,
                        sortModel,
                        filterModel: params.request.filterModel
                    });
                    
                    // 处理结果
                    if (response.data) {
                        const rowsThisPage = response.data.rows;
                        const totalCount = response.data.total;
                        const lastRow = totalCount <= params.request.endRow ? totalCount : -1;
                        
                        // 给AG Grid提供数据
                        params.success({
                            rowData: rowsThisPage,
                            rowCount: lastRow
                        });
                    } else {
                        params.fail();
                    }
                } catch (error) {
                    console.error('加载数据失败:', error);
                    params.fail();
                }
            }
        };
        params.api.setDatasource(dataSource);
    }, []);
    return (
        <div className="ag-theme-alpine" style={{ height: 500, width: '100%' }}>
            <AgGridReact
                ref={gridRef}
                columnDefs={[/* 列定义 */]}
                defaultColDef={{
                    flex: 1,
                    minWidth: 100,
                    resizable: true,
                    sortable: true,
                    filter: true
                }}
                rowModelType="infinite"
                cacheBlockSize={100}
                cacheOverflowSize={2}
                maxConcurrentDatasourceRequests={1}
                infiniteInitialRowCount={1000}
                maxBlocksInCache={10}
                onGridReady={onGridReady}
            />
        </div>
    );
}; 